# -*- coding: utf-8 -*-
# @Time : 2022/5/5 下午3:55
# @Author : wyf
# @FileName: server.py
# @Email: yunfei.wang@innvote.com

from concurrent import futures

import grpc

from modules.signModule.grpc_test.proto import test_pb2_grpc, test_pb2


class LogInterceptor(grpc.ServerInterceptor):
    """
    拦截器
    """
    def intercept_service(self, continuation, handler_call_details):
        print("请求开始")
        print(handler_call_details)
        print(handler_call_details.method)
        rsp = continuation(handler_call_details)
        print(continuation)
        print("请求结束")
        print(rsp)
        return rsp


class Greeter(test_pb2_grpc.GreeterServicer):

    def SayHello(self, request, context):
        from django.db import close_old_connections  # 每次连接前先断开旧的链接
        close_old_connections()
        persons = SignGroupPerson.objects.filter(plan_id=4)
        person_list = []
        for person in persons:
            p = test_pb2.Person()
            p.id = person.id
            p.name = person.face.name.encode("utf8")
            person_list.append(p)

        return test_pb2.SignInPersonList(message=f"你好1, {request.name}", person_list=person_list)


if __name__ == '__main__':
    import os
    import django
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'intelliface_dorm.settings')
    django.setup()  # 读取配置
    from modules.signModule.models import SignGroupPerson
    import logging
    logger = logging.getLogger('grpc')
    logger.info("----- RPC  服务开始 -----")
    # 实例化 日志拦截器
    log_interceptor = LogInterceptor()

    # 1. 实例化server
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10), interceptors=(log_interceptor,))
    # 2. 注册逻辑到server中
    test_pb2_grpc.add_GreeterServicer_to_server(Greeter(), server)
    # 3. 启动server
    server.add_insecure_port("[::]:50051")
    print("rpc server start at http://0.0.0.0:50051/")
    server.start()
    server.wait_for_termination()
